<?php
declare(strict_types=1);

namespace app\api\service;
use app\common\service\BaseService;
use app\common\model\Category as CategoryModel;



/**
 *商品分类服务类
 */
class Category extends BaseService
{
    public function getList($params):array
    {
        $condition = [];
        if(!empty($params['name'])){
            $condition[] = ['name','like',"%{$params['name']}%"];
        }
        $condition[] = ['is_show','=',1];
        $list = (new CategoryModel())->with(['image'])
            ->where($condition)
            ->select()
            ->each(function ($item){
                $item['image_url'] = $item['image_url'] ?? '';
            })
            ->toArray();
        return $this->getTreeData($list);
    }


    /**
     * 获取树状列表
     * @param $list
     * @param int $parentId
     * @return array
     */
    private function getTreeData($list, int $parentId = 0,$level = 0): array
    {
        $data = [];
        foreach ($list as $key => $item) {
            if ($item['parent_id'] == $parentId) {
                $item['level'] = $level;
                $children = $this->getTreeData($list, $item['category_id'],$level + 1);
                !empty($children) && $item['children'] = $children;
                $data[] = $item;
                unset($list[$key]);
            }
        }
        return $data;
    }


}